package com.sam.spring.security.controller;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * @classname: KaptchaImageController
 * @description: TODO
 * @Author: sam
 * @date: 2021/7/18 18:50
 */
@RestController
public class KaptchaImageController {
    /**
     * Kaptcha 配置
     */
    @Autowired
    private DefaultKaptcha defaultKaptcha;

    @GetMapping("/code")
    public void defaultKaptcha(HttpSession session, HttpServletResponse response) throws IOException {
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");

        // 生成验证码字符串并保存到 session 中
        String codeText = defaultKaptcha.createText();
        System.out.println("capText: " + codeText);
        session.setAttribute(Constants.KAPTCHA_SESSION_KEY, codeText);

        // 向客户端写出
        BufferedImage image = defaultKaptcha.createImage(codeText);
        try(ServletOutputStream out = response.getOutputStream()){
            ImageIO.write(image,"jpg",out);
        }
    }
}
